package com.ziroom.finance.rabbitmq.common.interceptor;

import com.ziroom.finance.rabbitmq.common.util.HttpUtil;
import com.ziroom.finance.rabbitmq.common.util.PageThreadLocal;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static com.ziroom.finance.rabbitmq.common.constant.Constant.DEFAULT_PAGE_SIZE;
import static com.ziroom.finance.rabbitmq.common.constant.Constant.DEFAULT_START_ROW;


/**
 * 请求包装类
 * Created by duxiaokang on 2016/11/2.
 */
@Component
@Aspect
public class RequestWrapperInterceptor implements Ordered {
    private static final Logger logger = LoggerFactory.getLogger(RequestWrapperInterceptor.class);

    /**
     * 示例
     * @author duxiaokang
     * @param joinPoint joinPoint
     */
    /*@Before("this(com.ziroom.finance.zwhite.api.ProjectController)")
    public void demoBefore(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        logger.info("进入信托专项计划controller的{}方法", name);
    }*/

    /**
     * 开启分页
     * @author duxiaokang
     * @param request request
     */
    @Before("execution(* com.ziroom.finance.zwhite.api.*.query*(..)) && args(request, ..)")
    public void startPage(HttpServletRequest request) {
        Integer beginRow = HttpUtil.getIntegerParameter(request, "beginRow");
        Integer pageSize = HttpUtil.getIntegerParameter(request, "pageSize");
        if (beginRow == null) {
            beginRow = DEFAULT_START_ROW;
        }
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        PageThreadLocal.startPage(beginRow, pageSize);
    }

    /**
     * 关闭分页
     * @author duxiaokang
     */
    @After("execution(* com.ziroom.finance.zwhite.api.*.query*(..))")
    public void clearPage() {
        PageThreadLocal.clear();
    }


    /**
     * 设置切面的优先级
     * @author  duxiaokang
     * @return  order
     */
    @Override
    public int getOrder() {
        // 设置切面顺序,越小越优先
        return 10;
    }
}
